import Uploader from 'simple-uploader.js'
import OSS from 'ali-oss'
import * as qiniu from 'qiniu-js'
import {message, notification} from 'ant-design-vue';
import {file_md5,trans} from '@/utils'
import token from '@/store/token'
import {ref} from "vue";
import request from '@/utils/axios'
import {responseHandel,responseBefore} from '@/utils/axios'
function noop() {
}

export default function useUploader(options) {

    let oss,loading
    const loadingText = ref()
    const event = {
        onSuccess: noop,
        onError: noop,
        onVerifyProgress: noop,
        onProgress: noop,
        onAddFile: noop,
        onFileSubmit: noop,
    }
    const config = {
        action: '',
        type: 'file',
        accessKey: '',
        secretKey: '',
        bucket: '',
        region: '',
        directory: '',
        domain: '',
        uploadToken: '',
        chunkSize: 1,
        chunk: true,
        disabled: false,
        isDirectory: false,
        multiple: false,
        progress: false,
        saveFinder: true,
        disk: 'local',
        driver: 'local',
        accept: '',
        params: {},
        headers: {},
        options: {},
    }
    options = Object.assign(config, options)
    if (options.driver === 'oss') {
        oss = new OSS({
            accessKeyId: options.accessKey,
            accessKeySecret: options.secretKey,
            bucket: options.bucket,
            region: options.region
        })
    }
    let uploader = new Uploader(Object.assign({
        target: options.action,
        query: (file) => {
            return Object.assign({
                type: options.type,
                file_type: file.fileType,
                directory: options.directory,
                disk: options.disk,
            }, options.params)
        },
        testChunks: options.chunk,
        chunkSize: options.chunk ? options.chunkSize * 1024 * 1024 : 10240 * 1024 * 1024,
        headers: Object.assign({Authorization: token.get(),'App-Name': window['App-Name'],Accept:'application/json, text/plain, */*'}, options.headers),
        checkChunkUploadedByResponse: options.chunk?function (chunk, message) {
            let objMessage = {}
            try {
                objMessage = JSON.parse(message)
            } catch (e) {
            }
            if ((objMessage.data.uploaded_chunks || []).indexOf(chunk.offset + 1) >= 0 || objMessage.data.url) {
                return true
            }
            return false
        }:null
    }, options.options))


    //文件添加触发
    uploader.on('fileAdded', function (file, e) {
        if (event.onAddFile(file, e) === false) {
            uploader.removeFile(file)
            return false;
        }

    })
    // uploader.on('fileAdded',fun)
    // 文件已经加入到上传列表中，一般用来开始整个的上传。
    uploader.on('filesSubmitted', function (files, fileList) {
        if (event.onFileSubmit(files, fileList) === false) {
            uploader.cancel()
        }
        files.forEach(file => {
            let fileMd5 = file_md5(file.file);
            file.pause()
            fileMd5.watch({
                progress: function (percentage) {
                    verifyProgress(percentage)
                },
                success: function (result) {
                    fileMd5 = null
                    file.uniqueIdentifier = result
                    if (options.driver == 'local' || options.type == 'image') {
                        file.resume()
                    }else{
                        if (options.driver === 'oss') {
                            ossUpload(file, getFileName(file))
                        } else if (options.driver === 'qiniu') {
                            qiniuUpload(file, getFileName(file))
                        }
                        uploader.removeFile(file)
                    }
                }
            })
        })
        uploader.upload()
        //进度message
        if(options.progress){
            const dom = document.getElementsByClassName('tox-dialog__footer')
            if(dom.length > 0){
                message.config({
                    getContainer:()=>dom[0],
                })
            }
            loading = message.loading({
                duration:0,
                prefixCls:dom.length > 0?'ex-message-upload ant-message':'ant-message',
                content:function () {
                    return loadingText.value
                }
            })
        }
    })

    //获取文件名
    function getFileName(file) {
        return options.directory + file.uniqueIdentifier + '.' + file.getExtension()
    }

    uploader.on('fileProgress', function (rootFile, file, chunk) {
        progress(parseInt(uploader.progress() * 100))
    })
    // 单个文件上传成功
    uploader.on('fileSuccess', function (rootFile, file, msg, chunk) {
        uploader.removeFile(file)
        try {
            const result = JSON.parse(msg)
            if (result.code === 200) {
                file.path = result.data.path
                success(file,result.data.url)
            }else if(result.code === 80010){
                closeLoading()
                if(result.data.type === 'success'){
                    event.onSuccess()
                }
                notification.open(responseBefore(result.data))
                return responseHandel(result.data)
            } else if(result.code === 80020){
                closeLoading()
                if(result.data.type === 'success'){
                    event.onSuccess()
                }
                message.open(responseBefore(result.data))
                return responseHandel(result.data)
            }  else {
                error(result.message)
            }
        } catch (e) {
            error()
        }
    })
    uploader.on('fileError', function (rootFile, file, msg, chunk) {
        uploader.removeFile(file)
        error(msg)
    })

    function input(element) {
        if (!options.disabled) {
            uploader.assignDrop(element)
            uploader.assignBrowse(element, options.isDirectory, !options.multiple, {
                accept: options.accept
            })
        }
    }
    //文件md5进度
    function verifyProgress(percentage) {
        loadingText.value =  trans('Uploader.check') + percentage + '%'
        event.onVerifyProgress(percentage)
    }
    //进度
    function progress(percentage) {
        loadingText.value =  trans('Uploader.uploading') + percentage + '%'
        event.onProgress(percentage)
    }
    function closeLoading() {
        if(loading){
            loading()
            message.destroy()
            message.config({
                getContainer:()=>document.body,
            })
        }
    }
    //成功
    function success(file,url) {
        closeLoading()
        if(options.saveFinder){
            request({
                url:'/ex-admin/system/upload',
                method:'post',
                data:{
                    data:{
                        cate_id:options.params.cate_id || 0,
                        type:file.fileType.indexOf('image')===0?'image':'file',
                        name:file.uniqueIdentifier + '.' + file.getExtension(),
                        real_name:file.name,
                        file_type:file.fileType,
                        url:url,
                        ext:file.getExtension(),
                        disk:options.disk,
                        path:file.path,
                        size:file.getSize(),
                    }
                }
            }).then(res=>{
                if(options.progress) {
                    message.success(trans('Uploader.success'))
                }
                event.onSuccess(url)
            })
        }else{
            if(options.progress) {
                message.success(trans('Uploader.success'))
            }
            event.onSuccess(url)
        }
    }
    //失败
    function error(msg) {
        closeLoading()
        if (!msg) {``
            msg = trans('Uploader.error')
        }
        message.error(msg)
        event.onError(msg)
    }

    //监听事件
    function watch(options) {
        //一个文件添加
        if (options.addFile) {
            event.onAddFile = options.addFile
        }
        //文件已经加入到上传列表中
        if (options.onFileSubmit) {
            event.onAddFile = options.fileSubmit
        }
        //成功
        if (options.success) {
            event.onSuccess = options.success
        }
        //失败
        if (options.error) {
            event.onError = options.error
        }
        //文件校验进度
        if (options.verifyProgress) {
            event.onVerifyProgress = options.verifyProgress
        }
        //进度
        if (options.progress) {
            event.onProgress = options.progress
        }
    }

    //阿里云上传
    function ossUpload(file, filename) {
        oss.multipartUpload(filename, file.file, {
            progress: function (percentage) {
                progress(parseInt(percentage * 100))
            }
        }).then(result => {
            const url = `${options.domain}/${filename}`
            file.path = filename
            success(file,url)
        }).catch((err) => {
            error(err.message)
        })
    }

    //七牛上传
    function qiniuUpload(file, filename) {
        const observable = qiniu.upload(file.file, filename, options.uploadToken, {
            fname: filename
        })
        observable.subscribe({
            next(res) {
                progress(parseInt(res.total.percent))
            },
            error(err) {
                error(err.message)
            },
            complete: () => {
                file.path = filename
                const url = `${options.domain}/${filename}`
                success(file,url)
            }
        })
    }
    return {uploader, watch, options, input}
}




